import { Button, Card, Form, Space, Input, Select, Table } from 'antd'
import { SearchOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react'
import { ColumnsType } from 'antd/es/table';
import { reqGetCityOrDistrict, reqGetHosTypes, reqGetHospitalList, reqGetProvince, reqUpdateHospitalStatus } from '@/api/hospital/hospitalList';
import { HospitalListItem, ProvinceItems, ReqGetHospitalSelParams } from '@/api/hospital/hospitalList/model/hospitalListTypes';
import type {Key} from 'react';
import { Link } from 'react-router-dom';
const { Option } = Select;

export default function HospitalList() {
  //声明状态
  let [provinces, setProvinces] = useState<ProvinceItems>([]);
  let [cities, setCities] = useState<ProvinceItems>([]);
  let [districts, setDistricts] = useState<ProvinceItems>([]);
  let [hostypes, setHostypes] = useState<ProvinceItems>([]);
  //医院列表的状态
  let [hospitals, setHospitals] = useState<HospitalListItem[]>([]);
  //分页相关的状态
  let [total, setTotal] = useState<number>(0);
  let [pageSize, setPageSize] = useState<number>(5);
  let [current, setCurrent] = useState<number>(1);
  let [loading, setLoading] = useState<boolean>(false);
  let [fieldsValue, setFieldsValue] = useState<ReqGetHospitalSelParams>({})
  let [form] = Form.useForm();
  let [fresh, setFresh] = useState<boolean>(false);
  //声明表单完成的回调函数
  let finish = () => {
    //获取表单中所有的数据
    let values = form.getFieldsValue();
    //更新状态
    setFieldsValue(values);
  }
  
  //表格结构
  let columns: ColumnsType<HospitalListItem> = [
    {
      title: '序号',
      render: (_, record, index) => index + 1
    },
    {
      title: '医院logo',
      render: (_, record) => {
        return <img width={100} src={'data:image/png;base64,' + record.logoData} alt="" />;
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname'
    },
    {
      title: '等级',
      render: (_, record) => {
        return record.param.hostypeString
      }
    },
    {
      title: '详细地址',
      render: (_, record) => {
        return record.param.fullAddress
      }
    },
    {
      // 0 未上线  1 已上线
      title: '状态',
      render: (_, record) => {
        return record.status === 1 ? '已上线' : '未上线'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime'
    },
    {
      title: '操作',
      render: (_, record) => {
        return <Space>
          <Link to={"/syt/hospital/show/" + record.id}><Button type="primary">查看</Button></Link>
          <Link to={"/syt/hospital/schedule/" + record.hoscode}><Button type="primary">排班</Button></Link>
          <Button onClick={async () => {
            //更新上下线状态
            await reqUpdateHospitalStatus(record.id, record.status ? 0 : 1);
            //刷新操作
            setFresh(!fresh);
          }} type="primary">{record.status === 0 ? '未上线' : '已上线'}</Button>
        </Space>
      }
    },
  ];

  //发送请求
  useEffect(() => {
    //获取省份信息
    let getData = async () => {
      //获取省份信息
      let result = await reqGetProvince();
      //更新状态
      setProvinces(result);
      //获取医院类型数据
      let hostypes = await reqGetHosTypes();
      //更新状态
      setHostypes(hostypes);
    }
    getData();
  }, []);

  //发送请求
  useEffect(() => {
    //写一个 async 函数
    (async () => {
      setLoading(true);
      //发送请求
      let result = await reqGetHospitalList({
        page: current,
        limit: pageSize,
        ...fieldsValue
      });
      //更新状态
      setHospitals(result.content);
      //更新分页数据的总数
      setTotal(result.totalElements);
      setLoading(false);
    })()
  }, [current, pageSize, fieldsValue, fresh]);

  //封装函数获取城市的列表
  let getCity = async (value: React.Key) => {
    //清空城市列表
    setCities([]);
    //清空区县列表
    setDistricts([]);
    //更改城市元素的值
    form.setFieldsValue({cityCode: undefined, districtCode: undefined});
    //发送请求
    let cities = await reqGetCityOrDistrict(value);
    //更新状态
    setCities(cities);
  }

  //封装函数获取区县的列表
  let getDistrict = async (value: Key) => {
    //清空区县的数据
    setDistricts([]);
    form.setFieldsValue({ districtCode: undefined});
    //发送请求
    let districts = await reqGetCityOrDistrict(value);
    //更新状态
    setDistricts(districts);
  }

  return (
    <Card>
      {/* 搜索区 */}
      <Form
        form={form}
        layout="inline"
        name="basic"
        autoComplete="off"
        onFinish={finish}
      >
        <Form.Item name="provinceCode" style={{ width: 200, marginRight: 20, }} >
          <Select
            onChange={getCity}
            placeholder="请选择省"
            allowClear
          >
            {/* 列表渲染 */}
            {
              provinces.map(item => {
                return <Option key={item.value} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>

        <Form.Item
          name="cityCode"
          style={{ width: 200, marginRight: 20 }}
        >
          <Select
            onChange={getDistrict}
            placeholder="请选择市"
            allowClear
          >
            {
              cities.map(item => {
                return <Option key={item.value} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>

        <Form.Item
          name="districtCode"
          style={{ width: 200, marginRight: 20 }}
        >
          <Select

            placeholder="请选择县"
            allowClear
          >
            {
              districts.map(item => {
                return <Option key={item.value} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item
          name="hosname"
        >
          <Input placeholder='医院名称' />
        </Form.Item>

        <Form.Item
          name="hoscode"
        >
          <Input placeholder='医院编号' />
        </Form.Item>

        <Form.Item
          name="hostype"
          style={{ width: 200, marginRight: 20 }}
        >
          <Select
            placeholder="医院类型"
            allowClear
          >
            {
              hostypes.map(item => {
                return <Option key={item.value} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>

        <Form.Item
          name="status"
          style={{ width: 200, marginRight: 20 }}
        >
          <Select
            placeholder="医院状态"
            allowClear
          >
            <Option value={1}>已上线</Option>
            <Option value={0}>未上线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
              查询
            </Button>
            <Button>
              清空
            </Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 表格区 */}
      <Table 
        loading={loading}
        bordered 
        columns={columns} 
        dataSource={hospitals} 
        rowKey={'id'}
        pagination={{
          current: current,
          total: total,
          pageSize: pageSize,
          showTotal: total => '总数为 ' + total,
          onChange: (page, pageSize) => {
            //更新状态
            setPageSize(pageSize);
            setCurrent(page);
          }
        }}
        />
    </Card>
  )
}
